package utils.groupsInfoHandler;

import bean.GroupInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import utils.fileHandler.FileHandler;
import utils.utilTime.UtilTime;

import java.util.List;
import java.util.Set;

import static utils.jsonHandler.JsonReadWrite.readJsonFile;
import static utils.jsonHandler.JsonReadWrite.writeJsonFile;

public class GroupsInfoHandler {
    private static JSONObject groupsObject;

    static {
        String path = FileHandler.getGroupInfoJSON();
        String s = readJsonFile(path);
        groupsObject = JSON.parseObject(s);
        if (groupsObject==null){
            groupsObject=new JSONObject();
        }
    }

    public static JSONObject getGroupsObject() {
        return groupsObject;
    }

    public static int getGroupsNumber() {
        return groupsObject.size();
    }

    public static Set<String> getGroupsName(){
        return groupsObject.keySet();
    }

    public static GroupInfo getGroupInfo(String name){
        JSONObject jsonObject = groupsObject.getJSONObject(name);
        GroupInfo groupInfo = new GroupInfo();
        groupInfo.setNumber(jsonObject.getInteger("number"));
        groupInfo.setKeyBoard(jsonObject.getJSONArray("keyBoard").toJavaList(String.class));
        JSONArray imagePath = jsonObject.getJSONArray("imagePath");
        groupInfo.setNumber(imagePath.size());
        groupInfo.setImagePath(imagePath.toJavaList(String.class));
        return groupInfo;
    }

    public synchronized static void save() {
        writeJsonFile(FileHandler.getGroupInfoJSON(), groupsObject.toString());
        System.out.println("Log : save "+FileHandler.getGroupInfoJSON()+" success"+ UtilTime.getStringTimeNow());
    }

    public synchronized static void exit(){
        save();
    }

    public static void addNewGroup(String name, GroupInfo groupInfo) {
        groupInfo.setGroupName(null);
        groupsObject.put(name, groupInfo);
    }

    public static void updateGroup(String name, GroupInfo groupInfo) {
        groupInfo.setGroupName(null);
        groupsObject.put(name,groupInfo);
    }

    public static void deleteGroup(String name) {
        groupsObject.remove(name);
    }

    public static void updateGroupName(String oldName, String newName) {
        JSONObject jsonObject = groupsObject.getJSONObject(oldName);
        groupsObject.put(newName, jsonObject);
    }

    public static void updateGroupKeyBoard(String name, List<String> keyBoard) {
        groupsObject.getJSONObject(name).put("keyBoard", keyBoard);
    }

    public static void updateGroupImageName(String name, List<String> imagePath) {
        JSONObject jsonObject = groupsObject.getJSONObject(name);
        jsonObject.put("number", imagePath.size());
        jsonObject.put("imagePath", imagePath);
        groupsObject.put(name, jsonObject);
    }
}